﻿using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using Sunny.UI;
using System;

namespace DevelopTool.Forms.DataConversionForms
{
    /// <summary>
    /// 存储容量换算
    /// </summary>
    public partial class StorageConversionForm : BaseUIPage
    {
        public StorageConversionForm()
        {
            InitializeComponent();
        }

        private void StorageConversionForm_Load(object sender, EventArgs e)
        {
            foreach (var control in this.uiTableLayoutPanel.Controls)
            {
                if (!(control is UITextBox textBox)) continue;

                textBox.GotFocus += UiTextBox_GotFocus;

                textBox.LostFocus += UiTextBox_LostFocus;
            }
        }

        /// <summary>
        /// 文本框获得焦点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UiTextBox_GotFocus(object sender, EventArgs e)
        {
            UITextBox uITextBox = sender as UITextBox;

            uITextBox.TextChanged += uiTextBox_TextChanged;
        }

        /// <summary>
        /// 文本框失去焦点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UiTextBox_LostFocus(object sender, EventArgs e)
        {
            UITextBox uITextBox = sender as UITextBox;

            uITextBox.TextChanged -= uiTextBox_TextChanged;
        }


        /// <summary>
        /// 清空TextBox的文本
        /// </summary>
        private void ClearTextBoxValue(UITextBox uITextBox)
        {
            foreach (var control in this.uiTableLayoutPanel.Controls)
            {
                if (!(control is UITextBox textBox)) continue;

                textBox.Text = string.Empty;
            }
        }

        /// <summary>
        /// 文本框值改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiTextBox_TextChanged(object sender, EventArgs e)
        {
            UITextBox uITextBox = sender as UITextBox;

            if (string.IsNullOrEmpty(uITextBox.Text))
            {
                ClearTextBoxValue(uITextBox);
                return;
            }

            if (!double.TryParse(uITextBox.Text, out double value)) return;

            StorageConversion(uITextBox.TagString, value);

        }


        /// <summary>
        /// 存储单位换算
        /// </summary>
        private void StorageConversion(string type, double value)
        {
            foreach (var control in this.uiTableLayoutPanel.Controls)
            {
                if (!(control is UITextBox textBox)) continue;

                if (textBox.TagString != type)
                    textBox.Text = StorageHelper.ConvertStorage(value, type, textBox.TagString).ToString();
            }
        }

    }
}
